// pages/future/future.js
// 不同天气对应不同图片，用于加载背景
const weatherMap = {
  '晴': 'sunny',
  '多云': 'cloudy',
  '阴': 'overcast',
  '小雨': 'lightrain',
  '大雨': 'heavyrain',
  '阵雨': 'shower',
  '雪': 'snow',
  '雨夹雪': 'sleet'
}
var app = getApp()

Page({


  data: {
    weekWeather: [],
    location: "成都市"
  },


  onLoad: function (options) {
    this.setData({
      location: app.globalData.city
    })

    
    var data = app.globalData.futureData;
    let futureWeather = JSON.parse(data)
    this.getFutureWeatherOffline(futureWeather)
  },
  onShow: function () {
    this.setData({
      location: app.globalData.city
    })


    this.getFutureWeather() },

  onPullDownRefresh: function () {
    this.getFutureWeather(() => {
      wx.stopPullDownRefresh()
    })
  },

  getFutureWeatherOffline(futureDataObj) {
    let weekWeather = []
    let result = futureDataObj

    for (var i = 0; i < 7; i++) {
      // 今天
      let day = new Date()
      day.setDate(day.getDate() + i)

      // 天气名处理
      var changeName = ''
      let realName = result[i].weather
      let endIndex = realName.indexOf('转')
      if (endIndex >= 0) {
        changeName = realName.substring(0, endIndex)
      } else {
        changeName = realName
      }

      weekWeather.push({
        week: `${result[i].week}`,
        date: `${day.getFullYear()}-${day.getMonth() + 1}-${day.getDate()}`,
        temp: `${result[i].temperature}`,
        icon: "/images/" + weatherMap[changeName] + "-icon.png",
      })
    }
    weekWeather[0].week = "今天"
    this.setData({
      weekWeather: weekWeather
    })
  },


  getFutureWeather(callback) {
    wx.request({
      url: 'https://v.juhe.cn/weather/index',
      data: {
        key: "c348a885dbbf7e2a2d50303b0fa869b0",
        cityname: this.data.location,
        format: 2
      },
      success: res => {
        //直接复用离线的代码渲染页面
        this.getFutureWeatherOffline(res.data.result.future)
      },
      complete: () => {
        callback && callback()
      }
    })
  }
})